<?php
class QrCodeAction extends UserAction{
	public function index(){
		date_default_timezone_set('PRC');
		$token_open=M('token_open')->field('queryname')->where(array(
				'token'=>session('token')))->find();
		if(!strpos($token_open['queryname'],'qrcode')){
			$this->error('您还开启该模块的使用权,请到功能模块中添加',U('Function/index',array(
					'token'=>session('token'),
					'id'=>session('wxid'))));
		}
		/* 获取临时二维码列表，展示 */
		$qrCodeModel=M('qrcode');
		$where['token']=session('token');
		$where['type']='1'; // 临时二维码
		$count=$qrCodeModel->where($where)->count();
		$totalLimitCount=$count;
		$pagelimit=new Page($count,10);
		$result=$qrCodeModel->where($where)->order('create_time DESC,status')->limit($pagelimit->firstRow.','.$pagelimit->listRows)->select();
		$return=array();
		foreach($result as $arr){
			$createTime=$arr['create_time'];
			$expireTime=$arr['expire_time'];
			$lastTime=$createTime+$expireTime;
			$arr['end_time']=(string)$lastTime;
			$where2=array(
					'qrscene_id'=>$arr['scene_id'],
					'ticket'=>$arr['ticket'],
					'token'=>$arr['token']);
			$qrAccessModel=M('qrcode_accessinfo');
			$accessCount=$qrAccessModel->where($where2)->count();
			if($accessCount==null){
				$accessCount=0;
			}
			$arr['accesscount']=$accessCount;
			$now=time();
			if($now>$lastTime&&$arr['status']=='1'){
				$arr['status']='0';
				$data['status']='0';
				$qrCodeModel->where("id=".$arr['id'])->save($data);
			}
			array_push($return,$arr);
		}
		$where['status']='1';
		$count=$qrCodeModel->where($where)->count();
		$usableLimit=$count;
		$this->assign('totalLimitCount',$totalLimitCount);
		$this->assign('usableLimitCount',$usableLimit);
		$this->assign('failedLimitCount',$totalLimitCount-$usableLimit);
		$this->assign('limitlist',$return);
		$this->assign('pagelimit',$pagelimit->show());
		
		/* 获取永久二维码列表，展示 */
		$qrCodeModel=M('qrcode');
		$where1['token']=session('token');
		$where1['type']='0'; // 永久二维码
		$count=$qrCodeModel->where($where1)->count();
		$usableUnLimitCount=$count;
		$pageunlimit=new Page($count,10);
		$result=$qrCodeModel->where($where1)->order('create_time DESC')->limit($pageunlimit->firstRow.','.$pageunlimit->listRows)->select();
		$return=array();
		foreach($result as $arr){
			$qrAccessModel=M('qrcode_accessinfo');
			$sceneid=$arr['scene_id'];
			$ticket=$arr['ticket'];
			$where3=array(
					'qrscene_id'=>$arr['scene_id'],
					'ticket'=>$arr['ticket'],
					'token'=>$arr['token']);
			$accessCount=$qrAccessModel->where($where3)->count();
			if($accessCount==null){
				$accessCount=0;
			}
			$arr['accesscount']=$accessCount;
			array_push($return,$arr);
		}
		
		$lastUnLimitCount=100000-$usableUnLimitCount;
		$listInfo="可用总量100000条 已建立".$usableUnLimitCount."条 剩余".$lastUnLimitCount."条";
		$this->assign('listInfo',$listInfo);
		$this->assign('unlimitlist',$return);
		$this->assign('pageunlimit',$pageunlimit->show());
		
		//获取分组信息
		$qrtype = M('qrcode_type')->select();
		
		foreach ($qrtype as $key=>$val){
			$q[$val['id']] = $val['name'];
		}
		$this->assign('qtype',$q);
		
		$this->display();
	}
	
	/**
	 * 展示二维码页面
	 */
	public function detail(){
		$id=$this->_get('id');
		$qrCodeModel=M('qrcode');
		$where['token']=session('token');
		$where['cms_id']=$id;
		$result=$qrCodeModel->where($where)->select();
		$userInfo['ticket']='https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.$result[0]['ticket'];
		$userInfo['id']=$id;
		$userInfo['info']=$result[0]['info'];
		$this->assign('userInfo',$userInfo);
		$this->display();
	}
	
	/**
	 * 创建临时二维码
	 */
	public function limitadd(){
		if(IS_POST){
			date_default_timezone_set('PRC');
			//$qrCodeInfo=$_POST['info'];
			$typeid = $_POST['typeid'];
			$expireSeconds=$_POST['expireTime'];
			// var_dump($qrCodeInfo);
			$result=null;
			$totalfailedCount=30;
			$count=0;
			$qrCodeModel=M('qrcode');
			do{
				$qrCodeSceneId=rand(1,100000000);
				$where['scene_id']=$qrCodeSceneId;
				$where['type']='1';
				$result=$qrCodeModel->where($where)->find();
				$count++;
			}while($result!=null&&$count<$totalfailedCount);
			if($count>=$totalfailedCount){
				$data='创建条目过多，请删除部分';
				$this->error($data);
			}
			$data=WechatAdvanceAPI::CreateQRLimitSence($qrCodeSceneId,$expireSeconds);
			if($data->errmsg!=null){
				$this->error($data);
			}else{
				// 获取二维码票号
				$ticket=$data->ticket;
				$where['token']=session('token');
				$where['ticket']=$ticket;
				$result=$qrCodeModel->where($where)->find();
				if($result!=null){
					$qrCodeModel->delete($where);
				}
				$qrCodeData['token']=session('token');
				$qrCodeData['scene_id']=$qrCodeSceneId;
				//$qrCodeData['info']=$qrCodeInfo;
				$qrCodeData['typeid'] = $typeid;
				$qrCodeData['create_time']=(string)time();
				$qrCodeData['expire_time']=(string)$data->expire_seconds;
				$qrCodeData['type']='1';
				$qrCodeData['ticket']=$data->ticket;
				$qrCodeData['cms_id']=md5($qrCodeData['create_time'].$ticket);
				$qrCodeData['status']='1';
				// 将票号存储到数据库
				if($id=$qrCodeModel->add($qrCodeData)){
					$this->success('临时二维码创建成功',U('QrCode/index',array(
							'token'=>session('token'))));
				}else{
					$this->error($data->getError());
				}
			}
		}else{
			$this->assign('types', $this->getQrType());
			$this->display();
		}
	}
	
	/**
	 * 创建永久二维码
	 */
	public function unlimitadd(){
		if(IS_POST){
			date_default_timezone_set('PRC');
			//$qrCodeInfo=$_POST['info'];
			$typeid = $_POST['typeid'];
			$qrCodeModel=M('qrcode');
			$result=null;
			$totalfailedCount=30;
			$count=0;
			// 找到数据库中最大的senceid
			$maxSceneId=$qrCodeModel->where('type = 0')->max('scene_id');
			if($maxSceneId==null){
				$maxSceneId=0;
			}
			$qrCodeSceneId=$maxSceneId+1;
			/* $where['info']=$qrCodeInfo;
			$result=$qrCodeModel->where($where)->select();
			if($result!=null){
				$this->error('数据库中有重复的用途编码:'.$info);
			} */
			$data=WechatAdvanceAPI::CreateQRUnLimitSence($qrCodeSceneId);
			
			// 如果抛出错误，那么打印出来
			if($data->errmsg!=null){
				$this->error($data);
			}else{
				// 获取二维码票号
				$ticket=$data->ticket;
				$where['token']=session('token');
				$where['ticket']=$ticket;
				$result=$qrCodeModel->where($where)->find();
				if($result!=null){
					$qrCodeModel->delete($where);
				}
				$qrCodeData['token']=session('token');
				$qrCodeData['scene_id']=$qrCodeSceneId;
				//$qrCodeData['info']=$qrCodeInfo;
				$qrCodeData['typeid'] = $typeid;
				$qrCodeData['create_time']=(string)time();
				$qrCodeData['expire_time']=' ';
				$qrCodeData['type']='0';
				$qrCodeData['ticket']=$data->ticket;
				$qrCodeData['cms_id']=md5($qrCodeData['create_time'].$ticket);
				$qrCodeData['status']='1';
				// var_dump($qrCodeData);
				// 将票号存储到数据库
				if($id=$qrCodeModel->add($qrCodeData)){
					$this->success('永久二维码创建成功',U('QrCode/index',array(
							'token'=>session('token'))));
				}else{
					$this->error($data->getError());
				}
			}
		}else{
			$this->assign('types', $this->getQrType());
			
			$this->display();
		}
	}
	
	/**
	 * 编辑临时二维码
	 */
	public function limitedit(){
		$qrCodeModel=M('qrcode');
		if(IS_POST){
			$qrCodeInfo=$_POST['info'];
			$qrCodeId=$_POST['id'];
			$data=array(
					'info'=>$qrCodeInfo);
			$qrCodeModel->where("id=".$qrCodeId)->save($data);
			$this->success('已成功修改',U('QrCode/index'));
		}else{
			$id=$this->_get('id');
			$where=array(
					'id'=>$id,
					'token'=>session('token'));
			$result=$qrCodeModel->where($where)->select();
			if($result[0]['status']=='0'){
				$this->error('该二维码已失效，无法进行修改',U('QrCode/index'));
			}
			$qrInfo=array(
					'info'=>$result[0]['info'],
					'id'=>$id);
			$this->assign('qrInfo',$qrInfo);
			$this->display();
		}
	}
	
	/**
	 * 编辑永久二维码
	 */
	public function unlimitedit(){
		$qrCodeModel=M('qrcode');
		if(IS_POST){
			$qrCodeInfo=$_POST['info'];
			$qrCodeId=$_POST['id'];
			$data=array(
					'info'=>$qrCodeInfo);
			$qrCodeModel->where("id=".$qrCodeId)->save($data);
			$this->success('已成功修改',U('QrCode/index'));
		}else{
			$id=$this->_get('id');
			$where=array(
					'id'=>$id,
					'token'=>session('token'));
			$result=$qrCodeModel->where($where)->select();
			if($result[0]['status']=='0'){
				$this->error('该二维码已失效，无法进行修改',U('QrCode/index'));
			}
			$qrInfo=array(
					'info'=>$result[0]['info'],
					'id'=>$id);
			$this->assign('qrInfo',$qrInfo);
			$this->display();
		}
	}
	
	/**
	 * 删除临时二维码
	 */
	public function limitdel(){
		$id=$this->_get('id');
		$where=array(
				'id'=>$id,
				'token'=>session('token'));
		$data=M('qrcode');
		$check=$data->where($where)->find();
		if($check==false)
			$this->error('非法操作');
		$back=$data->where($where)->delete();
		if($back==true){
			$this->success('删除成功');
		}else{
			$this->error('操作失败');
		}
	}
	
	/**
	 * 删除失效临时二维码
	 */
	public function limitfaileddel(){
		$where=array(
				'type'=>'1',
				'status'=>'0',
				'token'=>session('token'));
		$data=M('qrcode');
		$check=$data->where($where)->find();
		if($check==false){
			$this->success('没有失效的临时二维码');
			return;
		}
		$back=$data->where($where)->delete();
		if($back==true){
			$this->success('操作成功');
		}else{
			$this->error('操作失败');
		}
	}
	
	/**
	 * 删除永久二维码
	 */
	public function unlimitdel(){
		$id=$this->_get('id');
		$where=array(
				'id'=>$id,
				'token'=>session('token'));
		$data=M('qrcode');
		$check=$data->where($where)->find();
		if($check==false)
			$this->error('找不到该二维码');
		$qrCodeAccessModel = M('qrcode_accessinfo');
		$where1 = array(
			'qrscene_id'=> $check['scene_id'],
			'ticket'=>$check['ticket'],
			'token'=>session('token')
		);
		$check1=$qrCodeAccessModel->where($where1)->select();
		if($check1 == true) {
			$qrCodeAccessModel->where($where1)->delete();
		}
		
		$back=$data->where($where)->delete();
		if($back==true){
			$this->success('删除成功');
		}else{
			$this->error('操作失败');
		}
	}
	
	/**
	 * 批量创建永久二维码
	 */
	public function unlimitlistadd(){
		if(IS_POST){
			$key=$_POST['keyword'];
			$count=$_POST['count'];
			$start=$_POST['start'];
			$result=$this->CreateListQrCode($key,$start,$count);
			// var_dump($result);
			if($result['err']==''){
				$this->success('批量创建二维码成功！',U('QrCode/index'));
			}else{
				$err=$result['err'];
				$this->error("批量创建失败，原因:".$err);
			}
		}else{
			$this->display();
		}
	}
	/**
	 * 依据关键词批量删除永久二维码
	 * 
	 */
	public function unlimitlistdel() {
		$key=$_GET['searchkey'];
		$map['token']=$this->get('token');
		$map['info']=array(
				'like',
				"$key%");
		$qrCodeModel=M('qrcode');
		$check=$qrCodeModel->where($map)->find();
		if($check==false)
			$this->error('找不到指定的二维码');
		$data = $qrCodeModel->where($map)->select();
		$qrCodeAccessModel = M('qrcode_accessinfo');
		foreach($data as $arr){
			$where1 = array(
				'qrscene_id'=> $arr['scene_id'],
				'ticket'=>$arr['ticket'],
				'token'=>session('token')
			);
			$check1=$qrCodeAccessModel->where($where1)->select();
			if($check1 == true) {
				$qrCodeAccessModel->where($where1)->delete();
			}
		}
		$back=$qrCodeModel->where($map)->delete();
		if($back==true){
			$this->success('删除成功',U('QrCode/index'));
		}else{
			$this->error('操作失败');
		}
	}
	
	
	/**
	 * 批量创建二维码
	 * 
	 * @param unknown $key        	
	 * @param unknown $count        	
	 */
	private function CreateListQrCode($key,$start,$count){
		// 这个地方还有点逻辑问题，暂时没想好怎么再删除后再利用(能有10w条数据，一般不会遇到，所以这个暂时不考虑了
		$model=M('qrcode');
		// 找到数据库中最大的senceid
		$maxSceneId=$model->where('type = 0')->max('scene_id');
		if($maxSceneId==null){
			$maxSceneId=0;
		}
		for($currentCount=0;$currentCount<$count;$currentCount++){
			$info=$key.($start+$currentCount);
			$where['info']=$info;
			$result=$model->where($where)->select();
			if($result!=null){
				$return['err']='数据库中有重复的用途编码:'.$info;
				return $return;
			}
		}
		
		$thisSceneId=$maxSceneId+1;
		$currentCount=0;
		while($currentCount<$count){
			$maxErrCount=0;
			do{
				$result=$model->where('scene_id ='.$thisSceneId)->select();
				if(!$result){
					break;
				}
				$maxErrCount+=1;
				$thisSceneId+=1;
			}while($maxErrCount>30);
			if($maxErrCount>30){
				$return['err']="创建二维码数据过多，请批量删除再尝试";
				return $return;
			}
			$data=WechatAdvanceAPI::CreateQRUnLimitSence($thisSceneId);
			// 如果抛出错误，那么打印出来
			if($data->errmsg!=null){
				$return['err']=$data;
				return $return;
			}else{
				// 获取二维码票号
				$ticket=$data->ticket;
				$qrCodeData['token']=session('token');
				$qrCodeData['scene_id']=$thisSceneId;
				$qrCodeInfo=$key.($start+$currentCount);
				$qrCodeData['info']=$qrCodeInfo;
				$qrCodeData['create_time']=(string)time();
				$qrCodeData['expire_time']=' ';
				$qrCodeData['type']='0';
				$qrCodeData['ticket']=$data->ticket;
				$qrCodeData['cms_id']=md5($qrCodeData['create_time'].$ticket);
				$qrCodeData['status']='1';
				if($id=$model->add($qrCodeData)){
					$currentCount+=1;
					$thisSceneId+=1;
				}else{
					$return['err']=$data->getError();
					return $return;
				}
			}
		}
		return true;
	}
	
	/**
	 * 按关键词搜索永久二维码
	 */
	public function unlimitlistsearch(){
		if(IS_POST){
			$key=$this->_post('searchkey');
		}else if(IS_GET){
			$key=$_GET['searchkey'];
		}
		if($key!=null){
			$map['token']=$this->get('token');
			$map['info']=array(
					'like',
					"$key%");
			$qrCodeModel=M('qrcode');
			$count=$qrCodeModel->where($map)->count();
			$pageunlimit=new Page($count,20);
			$result=$qrCodeModel->where($map)->order('create_time DESC')->limit($pageunlimit->firstRow.','.$pageunlimit->listRows)->select();
			$return=array();
			foreach($result as $arr){
				$qrAccessModel=M('qrcode_accessinfo');
				$sceneid=$arr['scene_id'];
				$ticket=$arr['ticket'];
				$where=array(
						'qrscene_id'=>$arr['scene_id'],
						'ticket'=>$arr['ticket'],
						'token'=>$arr['token']);
				$accessCount=$qrAccessModel->where($where)->count();
				if($accessCount==null){
					$accessCount=0;
				}
				$arr['accesscount']=$accessCount;
				array_push($return,$arr);
			}
			
			$listInfo="按关键词\"".$key."\"搜索得到结果".$count."条";
			$this->assign('listInfo',$listInfo);
			$this->assign('unlimitlist',$return);
			$this->assign('pageunlimit',$pageunlimit->show());
			$this->assign('listCount',$count);
			$this->assign('searchkey',$key);
		}
		$this->display();
	}
	
	public function getunlimitlistsearchtxt(){
		$filename='output.txt';
		$encoded_filename=urlencode($filename);
		$encoded_filename=str_replace("+","%20",$encoded_filename);
		header("Content-Type: application/octet-stream");
		if(preg_match("/MSIE/",$_SERVER['HTTP_USER_AGENT'])){
			header('Content-Disposition:  attachment; filename="'.$encoded_filename.'"');
		}elseif(preg_match("/Firefox/",$_SERVER['HTTP_USER_AGENT'])){
			header('Content-Disposition: attachment; filename*="utf8'.$filename.'"');
		}else{
			header('Content-Disposition: attachment; filename="'.$filename.'"');
		}
		
		$key=$_GET['searchkey'];
		$map['token']=$this->get('token');
		$map['info']=array(
				'like',
				"$key%");
		$qrCodeModel=M('qrcode');
		$result=$qrCodeModel->where($map)->order('create_time DESC')->select();
		foreach($result as $arr){
			$info=$arr['info'];
			$cms_id=$arr['cms_id'];
			echo "二维码编号:http://".htmlspecialchars($_SERVER['HTTP_HOST'])."/index.php/qrcodeshow/".$cms_id."\t\t二维码用途:".$info."\r\n";
		}
	}
	
	public function typeadd(){
		if(IS_POST){
			$type = $this->_post('name');
			
			$data['name'] = $type;
			$id = M('qrcode_type')->add($data);
			if($id){
				$this->success('操作成功',U('QrCode/index'));
			}else{
				$this->success('操作失败，请检查数据',U('QrCode/index'));
			}			
		}else{
			$this->display();
		}
	}
	
	private function getQrType(){
		return M('qrcode_type')->field('id,name')->order('id asc')->select();
	}
	
}